import { defineStore } from 'pinia';
import piniaPersistConfig from "./piniaPersist";
import LocalCache from '@/utils/cache';

export const useTableStore = defineStore('table', {
  state: () => ({
    tableCaches: {} // 用一个对象来存储不同ID对应的表格状态
  }),
  getters: {
    getShowSearchById: (state) => (id, prefixes=["inqu_", "result_"]) => {
      const tempId = removePrefixesFn(id, prefixes)
      // 从缓存获取指定ID的showSearch状态
      const cacheKey = `table_${tempId}_showSearch`;
      return LocalCache.getCache(cacheKey) ?? true; // 默认值设为true，如果没有缓存则返回true
    }
  },
  actions: {
    updateSearchFormStatus(id, value, prefixes=["inqu_", "result_"]) {
      const tempId = removePrefixesFn(id, prefixes)
      // 更新指定ID表格的showSearch状态，并持久化到缓存
    //   const cacheKey = `table_${tempId}_showSearch`;
      this.tableCaches[tempId] = value;
    //   LocalCache.setCache(cacheKey, value);
      this.$patch({ tableCaches: this.tableCaches }); // 使用$patch确保状态变更被追踪
    },
    toggleSearchFormStatus(id, prefixes=["inqu_", "result_"]) {
      const tempId = removePrefixesFn(id, prefixes)
      // 切换指定ID表格的showSearch状态
      const currentValue = this.getShowSearchById(tempId);
      this.updateSearchFormStatus(tempId, !currentValue);
    },
    // 去除字符串前缀字段 
    // removePrefixes(str, prefixes=["inqu_", "result_"]) {
    //     if (typeof str !== 'string') {
    //         throw new Error('The first argument must be a string.');
    //     }
    //     if (!Array.isArray(prefixes)) {
    //         throw new Error('The second argument must be an array of prefixes.');
    //     }
    //     // 对于每一个前缀，如果字符串以该前缀开始，则移除之
    //     prefixes.forEach(prefix => {
    //         if (str.startsWith(prefix)) {
    //             str = str.substring(prefix.length);
    //         }
    //     });
    //     return str;
    // }
  },
  persist: piniaPersistConfig("table")
});
// 去除字符串前缀字段 
export function removePrefixesFn(str: string, prefixes: string[] = ["inqu_", "result_"]) {  

// export const removePrefixesFn = (str, prefixes=["inqu_", "result_"]) => { 
    if (typeof str !== 'string') {
        throw new Error('The first argument must be a string.');
    }
    if (!Array.isArray(prefixes)) {
        throw new Error('The second argument must be an array of prefixes.');
    }
    // 对于每一个前缀，如果字符串以该前缀开始，则移除之
    prefixes.forEach(prefix => {
        if (str.startsWith(prefix)) {
            str = str.substring(prefix.length);
        }
    });
    return str;
}